package com.cmq.web_1.cart;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = {"/cart"})
public class CartServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 从Session获取购物车（无登录，直接用Session）
        Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart");
        if (cart == null) {
            cart = new HashMap<>();
            session.setAttribute("cart", cart);
        }

        // 通过ProductDAO获取商品数据（确保不为null）
        Map<String, Product> products = ProductDAO.getAllProducts();

        // 传递数据到购物车页面
        request.setAttribute("products", products);
        request.setAttribute("cart", cart);
        calculateCartSummary(cart, request);

        request.getRequestDispatcher("/cart/cart.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        String productId = request.getParameter("productId");

        HttpSession session = request.getSession();
        Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart");
        if (cart == null) {
            cart = new HashMap<>();
            session.setAttribute("cart", cart);
        }

        // 验证商品是否存在（通过ProductDAO）
        Product product = ProductDAO.getProductById(productId);
        if (product == null && !"clear".equals(action)) {
            session.setAttribute("message", "商品不存在");
            response.sendRedirect(request.getContextPath() + "/cart/products.jsp");
            return;
        }

        // 处理购物车操作
        if ("add".equals(action)) {
            cart.put(productId, cart.getOrDefault(productId, 0) + 1);
            session.setAttribute("message", "商品已添加到购物车");
        } else if ("decrease".equals(action)) {
            int quantity = cart.getOrDefault(productId, 0);
            if (quantity > 1) {
                cart.put(productId, quantity - 1);
            } else {
                cart.remove(productId);
            }
            session.setAttribute("message", "商品数量已减少");
        } else if ("remove".equals(action)) {
            cart.remove(productId);
            session.setAttribute("message", "商品已移除");
        } else if ("clear".equals(action)) {
            cart.clear();
            session.setAttribute("message", "购物车已清空");
        } else {
            session.setAttribute("message", "无效操作");
        }

        response.sendRedirect(request.getContextPath() + "/cart");
    }

    // 计算总价和总数
    private void calculateCartSummary(Map<String, Integer> cart, HttpServletRequest request) {
        double totalPrice = 0.0;
        int totalQuantity = 0;
        for (Map.Entry<String, Integer> entry : cart.entrySet()) {
            Product p = ProductDAO.getProductById(entry.getKey()); // 使用DAO获取商品
            if (p != null) {
                int qty = entry.getValue();
                totalPrice += p.getPrice() * qty;
                totalQuantity += qty;
            }
        }
        request.setAttribute("totalPrice", totalPrice);
        request.setAttribute("totalQuantity", totalQuantity);
    }
}